import type { InternalAxiosRequestConfig } from 'axios'
import dayjs from 'dayjs'

const cacheToken: any = {}
let expirationTime: any = null

//添加博沃token请求头
export function addBwappJwtHeader(params: InternalAxiosRequestConfig<any>) {
    if (params.url?.indexOf('bwapp') !== -1) {
        const key =
            params.url?.indexOf('sxz') !== -1
                ? 'abd54bc8e-3bf8-4531-8c3e-a692ds22134'
                : 'bd54bc8e-3bf8-4531-8c3e-a692c9e70333'

        const currentTime = dayjs().valueOf()
        if (
            !expirationTime ||
            !cacheToken[key] ||
            (expirationTime && expirationTime <= currentTime)
        ) {
            const xhr = new XMLHttpRequest()
            xhr.open(
                'GET',
                `/out/bwapp/dataservice/sjcl/api/token_service/service/getToken?key=${key}`,
                false, // 同步
            )
            xhr.send()
            const res = JSON.parse(xhr.responseText)
            cacheToken[key] = res.data.TOKEN
            expirationTime = dayjs().add(10, 'minute').valueOf()
        }
        params.headers['jwt'] = cacheToken[key]
    }
}
